#include "Player.h"

#include "InputHandler.h"
#include "Utility.h"
#include "GameGlobals.h"
#include "Resources.h"

LINKCLASSTONAME("ent_player", Player);

Player::Player(sf::RenderWindow *App) : BaseMoveable(App)
{
	sf::Vector2f Points[4];
	float height, width;
	height = 99;
	width = 54;
	Points[0] = sf::Vector2f(-width / 2,height / 2);
	Points[1] = sf::Vector2f(width / 2, height / 2);
	Points[2] = sf::Vector2f(width / 2, -height / 2);
	Points[3] = sf::Vector2f(-width / 2, -height / 2);
	CreatePhysics();
	GetPhysicsObject()->PhysicsInitPolygon(this, Points, 4);
	GetPhysicsObject()->SetMass(200);

	Sprite.SetTexture(*Resources::Instance()->RequestImage("TankBody", true));

	sf::Vector2<float> Pos(0,0);
	SetPos(Pos);
	Sprite.SetOrigin(Sprite.GetSize().x / 2, Sprite.GetSize().y / 2);
	TankSpeed = 150.f;
	
	SetHealth(100.f);

	mTurret = EntityManager::Instance()->CreateEntity("ent_tankturret");
	mTurret->SetPos(GetPos());
	mTurret->SetOwner(this);

	Speed = 0.f;
}

Player::~Player(void)
{
}

void Player::OnTakeDamage(BaseEntity* inf, float Amount)
{
	if (inf->GetClass() == std::string("ent_shell") )
	{
		AddHealth(-Amount / 2.f);
	}
}

void Player::OnCollide(BaseMoveable *ent1, BaseMoveable *ent2, CollisionData CollideInfo)
{

}

void Player::Think()
{

	if (GetHealth() <= 0)
	{
		SetAlive(false);
		return;
	}

	float delta = GameGlobals::Instance()->FrameTime;

	float rot = Util::NormalizeAngle(Sprite.GetRotation());

	double x,y;
	x = sin(Util::DegToRad(rot));
	y = cos(Util::DegToRad(rot));

	sf::Vector2<float> MousePos;
	MousePos.x = float(sf::Mouse::GetPosition(*pRender).x);
	MousePos.y = float(sf::Mouse::GetPosition(*pRender).y);

	float TurretRot = -Util::Angle(InputHandler::GetMousePosWorld(*pRender), GetPos()) + 90.f;
	mTurret->SetAngle(Util::RotateTowards(mTurret->GetAngle(), TurretRot, 3.f));

	if (InputHandler::IsMouseButtonPressed(sf::Mouse::Left))
	{
		mTurret->Fire(std::string("shoot"));
	}

	if (InputHandler::IsKeyPressed(sf::Keyboard::W))
	{
		Speed = Util::Approach(Speed, TankSpeed, 1);
	}
	else if (InputHandler::IsKeyPressed(sf::Keyboard::S))
	{
		Speed = Util::Approach(Speed, -TankSpeed, -1);
	}
	else
	{
		Speed = Util::Approach(Speed, 0, -2);
	}

	//GetPhysicsObject()->ApplyForceOffset(sf::Vector2f(Speed * x * 100, Speed * y * 100), sf::Vector2f());
	GetPhysicsObject()->SetVelocity(sf::Vector2f(Speed * x, Speed * y));

	if (InputHandler::IsKeyPressed(sf::Keyboard::A))
	{
		GetPhysicsObject()->SetAngularVel(-50);
	}
	if (InputHandler::IsKeyPressed(sf::Keyboard::D))
	{
		GetPhysicsObject()->SetAngularVel(50);
	}
}

void Player::Draw()
{
	if (GetAlive())
	{
		Sprite.SetPosition(GetSFMLPos());
		Sprite.SetRotation(GetAngle());
		mTurret->SetPos(GetPos());
		pRender->Draw(Sprite);
		GetPhysicsObject()->Draw();
	}
}